<script setup lang="ts">
import { onMounted, reactive, ref } from "vue"
import {
  reqUserAdd,
  reqUserDelete,
  reqUserEdit,
  reqUserList,
  reqUserOptions,
  reqUserSetRole,
  reqUserStatus,
  reqDepOptions,
} from "@/api/user/user"
import type {
  ParamsData,
  RoleOptionResponse,
  RoleOptions,
  UserAddRoleParams,
  UserAddSaveParams,
  UserDepOptions,
  UserDepResult,
  UserEditSaveParams,
  UserListData,
  UserResponse,
  UserResponseData,
  UserResultResponse,
} from "@/api/types/user"
import { UserRules } from "@/common/rules.ts"
import { useXlsxDownload } from "@/hooks/export/export"
import { useUploadXlsx } from "@/hooks/import/import"
import { importUserUrl } from "@/api/uoload/uoloadUrl"

// 当前页
const current = ref<number>(1)
// 请求总条数
const limit = ref<number>(5)
// 总数
const total = ref<number>(0)
const searchValue = ref("")
const userList = ref<UserListData[]>([])
// 对话框显示隐藏
const dialogVisible = ref(false)
// 区别展示对应数据
const isWhose = ref(1)
// 对话框表单实例
const dialogFormRef = ref()
// 对话框表单校验
const dialogFormRules = {
  ...UserRules,
  name: [
    {
      required: true,
      min: 2,
      max: 5,
      message: "用户姓名必填",
      trigger: "blur",
    },
    {
      pattern: /^[\u4e00-\u9fa5]{2,4}$/,
      message: "用户姓名2-4位",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "用户手机号必填", trigger: "blur" },
    {
      pattern:
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/,
      message: "手机号不合规",
      trigger: "blur",
    },
  ],
}
// 用户详情
const userInfo = reactive<UserListData>({
  department: "",
  name: "",
  password: "",
  phone: "",
  role: [],
  status: false,
  username: "",
})
// 抽屉显示隐藏
const drawerVisible = ref(false)
// 抽屉表单用户信息
const roleDrawerForm = reactive({
  _id: "",
  username: "",
  name: "",
})
// 抽屉选中角色信息
const roleSelectedvalue = ref<string>()
// 抽屉选中部门信息
const depSelectedvalue = ref<string>()
// 抽屉角色列表信息
const RoleOptions = ref<RoleOptions[]>([])
// 抽屉部门列表信息
const DepOptions = ref<UserDepOptions[]>([])
// 获取用户列表
const getUserList = async (pages:number = 1) => {
  current.value = pages
  const params: ParamsData = {
    current: current.value,
    limit: limit.value,
    name: searchValue.value.trim(),
  }
  const { data: result }: UserResponseData = await reqUserList(params)
  userList.value = result.result
  current.value = Number(result.current)
  limit.value = Number(result.size)
  total.value = Number(result.total)
}

onMounted(() => {
  getUserList()
})

// 新增用户
const addUser = () => {
  dialogVisible.value = true
  isWhose.value = 3
}

// 重置搜索
const reset = () => {
  searchValue.value = ""
  getUserList()
}

// 处理用户状态切换
const handleStauts = async (data: UserListData) => {
  const resultStatus: UserResultResponse = await reqUserStatus(
    data._id as string,
    data.status
  )
  if (resultStatus.code == 201) {
    ElMessage.success(resultStatus.msg)
    getUserList(current.value)
    return
  }
  ElMessage.error(resultStatus.msg)
}

// 对话框处理
const handleClose = () => {
  cancelClose()
}
// 选择请求数量
const handleSizeChange = () => {
  getUserList()
}
// 抽屉关闭回掉
const handleDrawerClose = () => {
  drawerClose()
}
// 抽屉关闭
const drawerClose = () => {
  Object.assign(roleDrawerForm, {
    username: "",
    name: "",
  })
  roleSelectedvalue.value = ""
  depSelectedvalue.value = ""
  drawerVisible.value = false
}

// 获取角色信息 获取部门列表
const getRole = async (row: UserListData) => {
  drawerVisible.value = true
  //   角色列表数据
  const roleOption: RoleOptionResponse = await reqUserOptions()
  const depOption: UserDepResult = await reqDepOptions()
  //   赋值已选角色
  roleSelectedvalue.value = row.role![0]
  depSelectedvalue.value = row.department
  Object.assign(roleDrawerForm, row)
  // 赋值角色列表信息
  RoleOptions.value = roleOption.data.roleList
  // 赋值部门列表信息
  DepOptions.value = depOption.result
}
// 用户详情
const getInfo = (row: UserListData) => {
  dialogVisible.value = true
  isWhose.value = 1
  Object.assign(userInfo, row)
}
// 用户编辑
const getEdit = (row: UserListData) => {
  dialogVisible.value = true
  isWhose.value = 2
  // 赋值当前用户信息
  Object.assign(userInfo, row)
}
// 用户删除
const getDelete = async (id: string) => {
  const result: UserResultResponse = await reqUserDelete(id)
  if (result.code == 201) {
    getUserList()
    ElMessage.success(result.msg)
    return
  }
  ElMessage.error(result.msg)
}
// 对话框取消
const cancelClose = async () => {
  await dialogFormRef.value.resetFields()
  dialogVisible.value = false
  Object.assign(userInfo, {
    department: "",
    name: "",
    phone: "",
    password: "",
    role: [],
    status: null,
    username: "",
  })
}

// 角色列表改变赋值
const RoleSelect = (e: string) => {
  roleSelectedvalue.value = e
}
// 部门列表改变赋值
const depSelect = (e: string) => {
  depSelectedvalue.value = e
}
// 分配角色数据提交
const drawerSave = async () => {
  // 已经有角色ID
  const findRolID = RoleOptions.value.find(
    (v) =>
      v.roleName === roleSelectedvalue.value ||
      v._id === roleSelectedvalue.value
  )
  // 已经有部门ID
  const findDepID = DepOptions.value.find(
    (v) => v.name === depSelectedvalue.value || v._id === depSelectedvalue.value
  )
  const params: UserAddRoleParams = {
    id: roleDrawerForm._id,
    roleId: findRolID == undefined ? "" : findRolID!._id,
    departmentID: findDepID == undefined ? "" : findDepID!._id,
  }
  const result = await reqUserSetRole(params)
  if (result.code == 201) {
    ElMessage.success(result.msg)
    getUserList(current.value)
    roleSelectedvalue.value = ""
    depSelectedvalue.value = ""
    drawerVisible.value = false
    Object.assign(roleDrawerForm, {
      username: "",
      name: "",
    })
    return
  }
  ElMessage.error(result.msg)
}
// 提交数据
const save = async () => {
  if (isWhose.value === 2) {
    //   获取参数
    const params: UserEditSaveParams = {
      id: userInfo._id,
      newUsername: userInfo.username,
      newName: userInfo.name,
      newPhone: userInfo.phone,
    }
    //   编辑请求
    const result: UserResultResponse = await reqUserEdit(params)
    if (result.code == 201) {
      await dialogFormRef.value.resetFields()
      dialogVisible.value = false
      ElMessage.success(result.msg)
      getUserList(current.value)
      Object.assign(userInfo, {
        department: "",
        name: "",
        phone: "",
        password: "",
        role: [],
        status: null,
        username: "",
      })
      return
    }
    ElMessage.error(result.msg)
  }
  //   判断新增用户执行
  if (isWhose.value === 3) {
    // 注册参数
    const params: UserAddSaveParams = {
      username: userInfo.username,
      password: userInfo.password as string,
      name: userInfo.name,
      phone: userInfo.phone as number,
    }
    // 表单校验
    await dialogFormRef.value.validate()
    // 新增请求
    const result: UserResponse = await reqUserAdd(params)
    if (result.code == 201) {
      await dialogFormRef.value.resetFields()
      dialogVisible.value = false
      getUserList(
        (userList.value.length > 1
          ? current.value
          : (current.value as -1)) as number
      )
      ElMessage.success(result.msg)
      Object.assign(userInfo, {
        department: "",
        name: "",
        phone: "",
        password: "",
        role: [],
        status: null,
        username: "",
      })
      return
    }
    ElMessage.error(result.msg)
  }
}
// 用户导出
const expresData = () => {
  const headers = [
    "用户名",
    "手机号",
    "姓名",
    "角色",
    "部门",
    "状态",
    "创建时间",
    "更新时间",
    "上次登陆",
    "登陆IP",
  ]
  const exportData = userList.value.map((v) => {
    return {
      用户名: v.username,
      手机号: v.phone,
      姓名: v.name,
      角色: v.role?.join(","),
      部门: v.department,
      状态: v.status ? "开启" : "关闭",
      创建时间: v.createTime,
      更新时间: v.updateTime,
      上次登陆: v.lastTime,
      登陆IP: v.ip,
    }
  })
  useXlsxDownload(headers, exportData, "用户信息")
}
// 导入数据hooks函数
const { headers, handleSuccess, beforeUpload } = useUploadXlsx(() => {
  getUserList(current.value)
})
</script>

<template>
  <div class="user">
    <!-- 用户功能 -->
    <el-card class="top" >
      <el-row>
        <el-col :span="8" v-has="`User.btn.query`">
          <el-input
            v-model="searchValue"
            placeholder="请输入用户账号"
          ></el-input>
          <el-button
            :disabled="searchValue.trim().length > 0 ? false : true"
            @click="getUserList(1)"
            type="primary"
            >搜索</el-button
          >
          <el-button
            :disabled="searchValue.length > 0 ? false : true"
            @click="reset"
            type="info"
            >重置</el-button
          >
        </el-col>
        <el-col :span="3" v-has="`User.btn.Add`">
          <el-button  @click="addUser" type="primary">新增用户</el-button>
        </el-col>
        <el-col :span="3" v-has="`User.btn.export`">
          <el-upload
            class="upload-excel"
            :show-file-list="false"
            name="userXlsx"
            :headers="headers"
            :action="importUserUrl"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
          >
            <el-button type="success">用户导入</el-button>
          </el-upload>
        </el-col>
        <el-col :span="3">
          <el-button v-has="`User.btn.import`" type="info" @click="expresData">用户导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 分页展示 -->
    <el-card class="bottom">
      <el-table :data="userList" border>
        <el-table-column label="#" type="index" width="60" align="center" />
        <el-table-column
          label="用户账号"
          width="100"
          prop="username"
          align="center"
        />
        <el-table-column
          label="用户名"
          width="100"
          prop="name"
          align="center"
        />
        <el-table-column
          label="部门"
          width="100"
          prop="department"
          align="center"
        />
        <el-table-column label="角色" width="120" prop="role" align="center" />
        <el-table-column
          label="手机号"
          width="115"
          align="center"
          prop="phone"
        />
        <el-table-column v-has="`User.btn.Status`" label="状态" prop="status" align="center">
          <template #="{ row }">
            <el-switch @change="handleStauts(row)" v-model="row.status" />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          width="170"
          prop="createTime"
          align="center"
        ></el-table-column>
        <el-table-column
          label="修改时间"
          width="170"
          prop="updateTime"
          align="center"
        ></el-table-column>
        <el-table-column
          label="上次登陆时间"
          width="170"
          prop="lastTime"
          align="center"
        ></el-table-column>
        <el-table-column label="编辑" width="210" fixed="right" align="center">
          <template #="{ row }">
            <el-button
              type="success"
              @click="getInfo(row)"
              size="small"
              icon="InfoFilled"
            ></el-button>
            <el-button
              type="info"
              @click="getRole(row)"
              size="small"
              icon="Avatar"
              v-has="`User.btn.Allot`"
            ></el-button>
            <el-button
              v-has="`User.btn.Edit`"
              type="primary"
              @click="getEdit(row)"
              size="small"
              icon="Edit"
            ></el-button>
            <el-popconfirm
              @confirm="getDelete(row._id)"
              title="确认要删除该用户吗?"
            >
              <template #reference>
                <el-button v-has="`User.btn.delete`" type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="limit"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper, ->,total, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getUserList"
      />
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isWhose == 1 ? '用户信息' : '编辑用户'"
      width="600"
      :before-close="handleClose"
    >
      <template #header v-if="isWhose === 3">
        <h1>新增用户</h1>
      </template>
      <template #default>
        <el-form
          ref="dialogFormRef"
          :model="userInfo"
          :rules="dialogFormRules"
          class="dialogForm"
          label-width="70"
        >
          <el-row>
            <el-col :span="isWhose == 3 ? 24 : 12">
              <el-form-item label="账号" prop="username">
                <el-input
                  :disabled="isWhose == 1 ? true : false"
                  v-model="userInfo.username"
                ></el-input>
              </el-form-item>
              <el-form-item
                v-if="isWhose === 3 ? true : false"
                label="密码"
                prop="password"
              >
                <el-input v-model="userInfo.password"></el-input>
              </el-form-item>
              <el-form-item label="用户名" prop="name">
                <el-input
                  :disabled="isWhose == 1 ? true : false"
                  v-model="userInfo.name"
                ></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input
                  :disabled="isWhose == 1 ? true : false"
                  type="number"
                  v-model="userInfo.phone"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col v-if="isWhose == 3 ? false : true" :span="12">
              <el-form-item label="部门">
                <el-tag effect="dark" type="info" v-if="userInfo.department">{{
                  userInfo.department
                }}</el-tag>
              </el-form-item>
              <el-form-item label="角色">
                <el-tag
                  effect="dark"
                  type="primary"
                  v-if="userInfo.role"
                  v-for="item in userInfo.role"
                  >{{ item }}</el-tag
                >
              </el-form-item>
              <el-form-item label="状态">
                <el-tag
                  effect="dark"
                  type="success"
                  v-if="userInfo.status == true"
                  >开启</el-tag
                >
                <el-tag effect="dark" type="danger" v-else>关闭</el-tag>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelClose">取消</el-button>
          <el-button v-if="isWhose > 1" type="primary" @click="save">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 角色分配 抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="分配角色/职位"
      :before-close="handleDrawerClose"
    >
      <template #default>
        <el-form label-position="top">
          <el-form-item label="用户账号">
            <el-input
              :disabled="true"
              v-model="roleDrawerForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户姓名">
            <el-input :disabled="true" v-model="roleDrawerForm.name"></el-input>
          </el-form-item>
          <el-form-item label="分配角色">
            <el-select
              @change="RoleSelect"
              v-model="roleSelectedvalue"
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in RoleOptions"
                :key="item._id"
                :label="item.roleName"
                :value="item._id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="分配部门">
            <el-select
              v-model="depSelectedvalue"
              @change="depSelect"
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in DepOptions"
                :key="item._id"
                :label="item.name"
                :value="item._id"
                :disabled="!item.status"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="default" @click="drawerClose">取消</el-button>
        <el-button
          type="primary"
          @click="drawerSave"
          :disabled="roleSelectedvalue && depSelectedvalue ? false : true"
          >确认</el-button
        >
      </template>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.user {
  // 功能样式
  .top {
    margin-bottom: 20px;
    .el-input {
      width: 140px;
      margin-right: 10px;
    }
  }
  //   列表分页样式
  .bottom {
    .el-pagination {
      margin-top: 20px;
    }
  }
}
</style>
